CROSS_COMPILE = riscv64-unknown-elf-
CC = $(CROSS_COMPILE)gcc
LD = $(CROSS_COMPILE)ld
OBJDUMP = $(CROSS_COMPILE)objdump
NM = $(CROSS_COMPILE)nm

CFLAGS = -mcmodel=medany -ffreestanding -fno-common -nostdlib -mno-relax -ggdb -O0 -I./include
ASFLAGS = -mcmodel=medany
LDFLAGS = -z max-page-size=4096

OBJS = kernel/entry.o kernel/main.o kernel/uart.o kernel/printf.o kernel/spinlock.o kernel/console.o kernel/printf_test.o
KERNEL = kernel.elf

all: $(KERNEL)

$(KERNEL): $(OBJS) kernel/kernel.ld
	$(LD) $(LDFLAGS) -T kernel/kernel.ld -o $@ $(OBJS)

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.S
	$(CC) $(ASFLAGS) -c $< -o $@

run: $(KERNEL)
	qemu-system-riscv64 -machine virt -bios none -kernel $(KERNEL) -nographic

qemu: run

check: $(KERNEL)
	$(OBJDUMP) -h $(KERNEL)
	$(NM) $(KERNEL) | grep -E "(entry|text|data|bss|stack|end)"

clean:
	rm -f $(OBJS) $(KERNEL)

.PHONY: all run qemu check clean